import re

import pandas as pd
from flask import Flask, render_template, request, g, current_app

from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Bar, Pie, Timeline, Tab, Grid, Sunburst, WordCloud, Map, Page, Liquid, Radar, Line, Funnel

# import sys
# sys.setrecursionlimit(100000)

app = Flask(__name__)


def myreplace(x):
    x = x.replace('私营企业和个体就业人员', '')
    x = x.replace('城镇单位就业人员', '')
    x = x.replace('城镇私营企业和个体就业人员', '')
    x = x.replace('城镇单位就业人员平均工资', '')
    x = x.replace('城镇私营单位就业人员平均工资', '')
    x = x.replace('平均工资', '')
    x = x.replace('工资总额指数', '')
    x = x.replace('工资总额', '')
    return x


class GetData:
    def __init__(self):
        self.df = pd.read_csv('work_data.csv', encoding='utf-8')
        # df.shape
        self.df.drop_duplicates(inplace=True)
        self.df.fillna(0, inplace=True)
        self.huafeng = {'华东': ['上海', '江苏', '浙江', '安徽', '江西', '山东', '福建'],
                        '华北': ['北京', '天津', '山西', '河北', '内蒙古'],
                        '华中': ['河南', '湖北', '湖南'],
                        '华南': ['广东', '广西', '海南'],
                        '西南': ['重庆', '四川', '贵州', '云南', '西藏'],
                        '西北': ['陕西', '甘肃', '青海', '宁夏', '新疆'],
                        '东北': ['黑龙江', '吉林', '辽宁']
                        }

        def fun(x):
            x = x.replace('省', '')
            x = x.replace('维吾尔自治区', '')
            x = x.replace('自治区', '')
            x = x.replace('壮族', '')
            x = x.replace('回族', '')
            x = x.replace('市', '')
            return x

        def industry_fun(x):
            x = x.replace('农、林、牧、渔业城镇私营单位就业人员平均工资', '农林牧渔业城镇私营单位就业人员平均工资')
            x = x.replace('电力、燃气及水的生产和供应业城镇私营单位就业人员平均工资', '电力、热力、燃气及水生产和供应业城镇私营单位就业人员平均工资')
            x = x.replace('信息传输、计算机服务和软件业城镇私营单位就业人员平均工资', '信息传输、软件和信息技术服务业城镇私营单位就业人员平均工资')
            x = x.replace('科学研究、技术服务和地质勘查业城镇私营单位就业人员平均工资', '科学研究和技术服务业城镇私营单位就业人员平均工资')
            x = x.replace('居民服务和其他服务业城镇私营单位就业人员平均工资', '居民服务、修理和其他服务业城镇私营单位就业人员平均工资')
            x = x.replace('教育城镇私营单位就业人员平均工资', '教育业城镇私营单位就业人员平均工资')
            x = x.replace('卫生、社会保障和社会福利业城镇私营单位就业人员平均工资', '卫生和社会工作城镇私营单位就业人员平均工资')
            x = x.replace('公共管理和社会组织城镇私营单位就业人员平均工资', '文化、体育和娱乐业城镇私营单位就业人员平均工资')
            x = x.replace('农、林、牧、渔业城镇单位就业人员平均工资', '农林牧渔业城镇单位就业人员平均工资')
            x = x.replace('电力、燃气及水的生产和供应业城镇单位就业人员平均工资', '电力、热力、燃气及水生产和供应业城镇单位就业人员平均工资')
            x = x.replace('信息传输、计算机服务和软件业城镇单位就业人员平均工资', '信息传输、软件和信息技术服务业城镇单位就业人员平均工资')
            x = x.replace('科学研究、技术服务和地质勘查业城镇单位就业人员平均工资', '科学研究和技术服务业城镇单位就业人员平均工资')
            x = x.replace('居民服务和其他服务业城镇单位就业人员平均工资', '居民服务、修理和其他服务业城镇单位就业人员平均工资')
            x = x.replace('教育城镇单位就业人员平均工资', '教育业城镇单位就业人员平均工资')
            x = x.replace('卫生、社会保障和社会福利业城镇单位就业人员平均工资', '卫生和社会工作城镇单位就业人员平均工资')
            x = x.replace('公共管理和社会组织城镇单位就业人员平均工资', '公共管理、社会保障和社会组织城镇单位就业人员平均工资')
            return x

        self.df['city'] = self.df['city'].apply(lambda x: fun(x))
        self.df['industry'] = self.df['industry'].apply(lambda x: industry_fun(x))
        self.work_hangye_chengzhen = self.df.query('industry == "农林牧渔业城镇单位就业人员"or industry == "采矿业城镇单位就业人员" \
                                 or industry == "制造业城镇单位就业人员" or industry == "电力、热力、燃气及水生产和供应业城镇单位就业人员" \
                                 or industry == "建筑业城镇单位就业人员" or industry == "交通运输、仓储和邮政业城镇单位就业人员" \
                                 or industry == "信息传输、软件和信息技术服务业城镇单位就业人员" or industry == "批发和零售业城镇单位就业人员" \
                                 or industry == "住宿和餐饮业城镇单位就业人员" or industry == "金融业城镇单位就业人员" \
                                 or industry == "房地产业城镇单位就业人员" or industry == "租赁和商务服务业城镇单位就业人员"\
                                 or industry == "科学研究和技术服务业城镇单位就业人员" or industry == "水利、环境和公共设施管理业城镇单位就业人员" \
                                 or industry == "居民服务、修理和其他服务业城镇单位就业人员" or industry == "教育业城镇单位就业人员"\
                                 or industry == "卫生和社会工作城镇单位就业人员" or industry == "文化、体育和娱乐业城镇单位就业人员"\
                                 or industry == "公共管理、社会保障和社会组织城镇单位就业人员"')
        self.work_hangye_sige = self.df.query('industry == "制造业私营企业和个体就业人员" \
                                 or industry == "建筑业私营企业和个体就业人员" or industry == "交通运输、仓储和邮政业私营企业和个体就业人员"\
                                 or industry == "批发和零售业私营企业和个体就业人员" or industry == "住宿和餐饮业私营企业和个体就业人员"\
                                 or industry == "租赁和商务服务业私营企业和个体就业人员" or industry == "居民服务和其他服务业私营企业和个体就业人员"')
        self.work_hangye_chengzhen_sige = self.df.query('industry == "城镇私营企业和个体就业人员" or industry =="制造业城镇私营企业和个体就业人员"\
                                 or industry =="建筑业城镇私营企业和个体就业人员"or industry =="交通运输、仓储和邮政业城镇私营企业和个体就业人员"\
                                 or industry =="批发和零售业城镇私营企业和个体就业人员"or industry =="住宿和餐饮业城镇私营企业和个体就业人员"\
                                 or industry =="租赁和商务服务业城镇私营企业和个体就业人员"or industry =="居民服务和其他服务业城镇私营企业和个体就业人员"')
        self.work_siying = self.df.query('industry == "私营企业户数" or industry == "私营企业就业人数" or industry == "私营企业投资者就业人数" \
                                 or industry == "城镇私营企业就业人数" or industry == "城镇私营企业投资者就业人数" \
                                 or industry == "乡村私营企业就业人数" or industry == "乡村私营企业投资者就业人数"')
        self.work_geti = self.df.query(
            'industry == "个体户数" or industry == "个体就业人数" or industry == "城镇就业人数" or industry == "乡村个体就业人数"')
        self.wage_chengzhen_zong = self.df.query('industry == "城镇单位就业人员工资总额" or industry == "国有城镇单位就业人员工资总额"\
                                 or industry == "城镇集体单位就业人员工资总额" or industry == "其他城镇单位就业人员工资总额"\
                                 or industry == "城镇单位就业人员工资总额指数(上年=100)" or industry == "国有城镇单位就业人员工资总额指数(上年=100)" \
                                 or industry == "城镇集体单位就业人员工资总额指数(上年=100)" or industry == "其他城镇单位就业人员工资总额指数(上年=100)"')
        self.wage_chengzhen_pingjun = self.df.query('industry == "城镇单位就业人员平均工资" or industry == "城镇单位在岗职工平均工资" or industry == "城镇国有单位就业人员平均工资"\
                                 or industry == "城镇集体单位就业人员平均工资" or industry == "城镇其他单位就业人员平均工资" or industry == "城镇单位就业人员平均货币工资指数(上年=100)" \
                                 or industry == "城镇单位在岗职工平均货币工资指数(上年=100)" or industry == "国有城镇单位就业人员平均货币工资指数(上年=100)" or industry == "城镇集体单位就业人员平均货币工资指数(上年=100)"\
                                 or industry == "其他城镇单位就业人员平均货币工资指数(上年=100)" or industry == "城镇单位就业人员平均实际工资指数(上年=100)" or industry == "城镇单位在岗职工平均实际工资指数(上年=100)"\
                                 or industry == "国有城镇单位就业人员平均实际工资指数(上年=100)" or industry == "城镇集体单位就业人员平均实际工资指数(上年=100)" or industry == "其他城镇单位就业人员平均实际工资指数(上年=100)"')
        self.wage_zhuce_chengzhen_pingjun = self.df.query('industry == "城镇单位就业人员平均工资" or industry == "国有单位就业人员平均工资" or industry == "城镇集体单位就业人员平均工资" \
                                 or industry == "股份合作单位就业人员平均工资" or industry == "联营单位就业人员平均工资" or industry == "有限责任公司就业人员平均工资" \
                                 or industry == "股份有限公司就业人员平均工资" or industry == "其他单位就业人员平均工资" or industry == "港、澳、台商投资单位就业人员平均工资" \
                                 or industry == "外商投资单位就业人员平均工资"')
        self.wage_hangye_chengzhen_zong = self.df.query('industry == "农、林、牧、渔业城镇单位就业人员工资总额" or industry =="城镇单位就业人员工资总额" or industry == "采矿业城镇单位就业人员工资总额" \
                                 or industry == "制造业城镇单位就业人员工资总额" or industry == "电力、燃气及水的生产和供应业城镇单位就业人员工资总额" \
                                 or industry == "建筑业城镇单位就业人员工资总额" or industry == "交通运输、仓储和邮政业城镇单位就业人员工资总额" \
                                 or industry == "信息传输、计算机服务和软件业城镇单位就业人员工资总额" or industry == "批发和零售业城镇单位就业人员工资总额" \
                                 or industry == "住宿和餐饮业城镇单位就业人员工资总额" or industry == "金融业城镇单位就业人员工资总额" \
                                 or industry == "房地产业城镇单位就业人员工资总额" or industry == "租赁和商务服务业城镇单位就业人员工资总额"\
                                 or industry == "科学研究、技术服务和地质勘查业城镇单位就业人员工资总额" or industry == "水利、环境和公共设施管理业城镇单位就业人员工资总额" \
                                 or industry == "居民服务和其他服务业城镇单位就业人员工资总额" or industry == "教育城镇单位就业人员工资总额"\
                                 or industry == "卫生、社会保障和社会福利业城镇单位就业人员工资总额" or industry == "文化、体育和娱乐业城镇单位就业人员工资总额"\
                                 or industry == "公共管理和社会组织城镇单位就业人员工资总额"')
        self.wage_hangye_chengzhen_pingjun = self.df.query('industry == "农林牧渔业城镇单位就业人员平均工资"or industry == "采矿业城镇单位就业人员平均工资" \
                                 or industry == "制造业城镇单位就业人员平均工资" or industry == "电力、热力、燃气及水生产和供应业城镇单位就业人员平均工资" \
                                 or industry == "建筑业城镇单位就业人员平均工资" or industry == "交通运输、仓储和邮政业城镇单位就业人员平均工资" \
                                 or industry == "信息传输、软件和信息技术服务业城镇单位就业人员平均工资" or industry == "批发和零售业城镇单位就业人员平均工资" \
                                 or industry == "住宿和餐饮业城镇单位就业人员平均工资" or industry == "金融业城镇单位就业人员平均工资" \
                                 or industry == "房地产业城镇单位就业人员平均工资" or industry == "租赁和商务服务业城镇单位就业人员平均工资"\
                                 or industry == "科学研究和技术服务业城镇单位就业人员平均工资" or industry == "水利、环境和公共设施管理业城镇单位就业人员平均工资" \
                                 or industry == "居民服务、修理和其他服务业城镇单位就业人员平均工资" or industry == "教育业城镇单位就业人员平均工资"\
                                 or industry == "卫生和社会工作城镇单位就业人员平均工资" or industry == "文化、体育和娱乐业城镇单位就业人员平均工资"\
                                 or industry == "公共管理、社会保障和社会组织城镇单位就业人员平均工资"')
        self.wage_hangye_chengzhensiying_pingjun = self.df.query('industry == "农林牧渔业城镇私营单位就业人员平均工资"or industry == "采矿业城镇私营单位就业人员平均工资" \
                                 or industry == "制造业城镇私营单位就业人员平均工资" or industry == "电力、热力、燃气及水生产和供应业城镇私营单位就业人员平均工资" \
                                 or industry == "建筑业城镇私营单位就业人员平均工资" or industry == "交通运输、仓储和邮政业城镇私营单位就业人员平均工资" \
                                 or industry == "信息传输、软件和信息技术服务业城镇私营单位就业人员平均工资" or industry == "批发和零售业城镇私营单位就业人员平均工资" \
                                 or industry == "住宿和餐饮业城镇私营单位就业人员平均工资" or industry == "金融业城镇私营单位就业人员平均工资" \
                                 or industry == "房地产业城镇私营单位就业人员平均工资" or industry == "租赁和商务服务业城镇私营单位就业人员平均工资"\
                                 or industry == "科学研究和技术服务业城镇私营单位就业人员平均工资" or industry == "水利、环境和公共设施管理业城镇私营单位就业人员平均工资" \
                                 or industry == "居民服务、修理和其他服务业城镇私营单位就业人员平均工资" or industry == "教育业城镇私营单位就业人员平均工资"\
                                 or industry == "卫生和社会工作城镇私营单位就业人员平均工资" or industry == "文化、体育和娱乐业城镇私营单位就业人员平均工资"\
                                 or industry == "公共管理、社会保障和社会组织城镇私营单位就业人员平均工资"')
        self.shiye = self.df.query('industry == "城镇登记失业人数" or industry == "城镇登记失业率"')
        self.city = ['新疆', '宁夏', '青海', '甘肃', '陕西', '西藏', '云南', '贵州', '四川', '重庆', '海南', '广西', '广东'
            , '湖南', '湖北', '河南', '山东', '江西', '福建', '安徽', '浙江', '江苏', '上海', '黑龙江', '吉林', '辽宁', '内蒙古'
            , '山西', '河北', '天津', '北京']
        self.fenlei = ['按行业分城镇单位就业人员', '按行业分私营企业和个体就业人员', '按行业分城镇私营企业和个体就业人员',
                       '私营企业就业人员', '个体就业人员', '城镇单位就业人员工资总额和指数', '城镇单位就业人员平均工资和指数',
                       '按登记注册类型分城镇单位就业人员平均工资', '按行业分城镇单位就业人员工资总额',
                       '按行业分城镇单位就业人员平均工资', '按行业分城镇私营单位就业人员平均工资', '城镇登记失业人员及失业率']
        self.fenlei_min = ["农林牧渔业城镇单位就业人员", "采矿业城镇单位就业人员", "制造业城镇单位就业人员", "电力、热力、燃气及水生产和供应业城镇单位就业人员"
            , "建筑业城镇单位就业人员", "交通运输、仓储和邮政业城镇单位就业人员", "信息传输、软件和信息技术服务业城镇单位就业人员", "批发和零售业城镇单位就业人员"
            , "住宿和餐饮业城镇单位就业人员", "金融业城镇单位就业人员", "房地产业城镇单位就业人员", "租赁和商务服务业城镇单位就业人员", "科学研究和技术服务业城镇单位就业人员"
            , "水利、环境和公共设施管理业城镇单位就业人员", "居民服务、修理和其他服务业城镇单位就业人员", "教育业城镇单位就业人员", "卫生和社会工作城镇单位就业人员"
            , "文化、体育和娱乐业城镇单位就业人员", "公共管理、社会保障和社会组织城镇单位就业人员"]

    def get_data(self, fenlei):
        if fenlei is None:
            return None
        if fenlei == self.fenlei[0]:
            return self.work_hangye_chengzhen
        elif fenlei == self.fenlei[1]:
            return self.work_hangye_sige
        elif fenlei == self.fenlei[2]:
            return self.work_hangye_chengzhen_sige
        elif fenlei == self.fenlei[3]:
            return self.work_siying
        elif fenlei == self.fenlei[4]:
            return self.work_geti
        elif fenlei == self.fenlei[5]:
            return self.wage_chengzhen_zong
        elif fenlei == self.fenlei[6]:
            return self.wage_chengzhen_pingjun
        elif fenlei == self.fenlei[7]:
            return self.wage_zhuce_chengzhen_pingjun
        elif fenlei == self.fenlei[8]:
            return self.wage_hangye_chengzhen_zong
        elif fenlei == self.fenlei[9]:
            return self.wage_hangye_chengzhen_pingjun
        elif fenlei == self.fenlei[10]:
            return self.wage_hangye_chengzhensiying_pingjun
        elif fenlei == self.fenlei[11]:
            print("1")
            return self.shiye


class DataStroe():
    fenlei = None
    city = None
    map_data = None
    map_industry = None
    map_city = None


data = DataStroe()


@app.route('/')
def hello_world():  # put application's code here
    return render_template("index.html")


@app.route('/index', methods=['POST', 'GET'])
def index():  # put application's code here

    mydata = GetData()
    DF = mydata.get_data('按行业分城镇单位就业人员')
    fenleis = mydata.fenlei
    citys = mydata.city
    data_list = DF.query('city == "甘肃"')
    data_list = data_list.iterrows()
    head = '甘肃省-按行业分城镇单位就业人员'
    if request.method == 'POST':
        fenlei = request.form.get('fenlei')
        city = request.form.get('city')
        print("分类:", fenlei)
        head = city + '-' + fenlei
        post_data = GetData()
        datali = post_data.get_data(fenlei)
        if datali is not None:
            data_list = datali.query('city == "{}"'.format(city))
            data_list = data_list.iterrows()
        else:
            data_list = []
        return render_template('index.html', datalist=data_list, citys=citys, fenleis=fenleis, head=head)

    return render_template("index.html", datalist=data_list, citys=citys, fenleis=fenleis, head=head)


@app.route('/bar', methods=['POST', 'GET'])
def bar():
    mydata = GetData()
    DF = mydata.get_data('按行业分城镇单位就业人员')
    fenleis = mydata.fenlei
    citys = mydata.city
    data_list = DF.query('city == "甘肃"')
    data_list = data_list.iterrows()
    data.fenlei = '按行业分城镇单位就业人员'
    data.city = '甘肃'
    if request.method == 'POST':
        if fenleis is not None:
            data.fenlei = request.form.get('fenlei')
            data.city = request.form.get('city')
        else:
            return render_template("bar.html", datalist=data_list, citys=citys, fenleis=fenleis)
    return render_template("bar.html", datalist=data_list, citys=citys, fenleis=fenleis)


@app.route("/bar_pie")
def get_bar_chart():
    fenlei = data.fenlei
    city = data.city
    print(fenlei)
    print(city)
    timeline = Timeline(init_opts=opts.InitOpts(width="1600px", height="900px"))

    for y in range(2012, 2021):
        timeline.add(bar_pie(fenlei, city, year=y), time_point=str(y))
    timeline.add_schema(is_timeline_show=False, orient='vertical', is_auto_play=True, play_interval=1500, pos_left='10',
                        pos_top='10')
    return timeline.dump_options_with_quotes()


def bar_pie(fenlei, city, year):
    bar = bar_base(fenlei, city, year)
    pie = pie_base(fenlei, city, year)
    return bar.overlap(pie)


def bar_base(fenlei, city, year) -> Bar:
    mydata = GetData()
    work_hangye_chengzhen = mydata.get_data(fenlei)
    work = work_hangye_chengzhen.query('city == "{}"'.format(city))
    work = work.sort_values(by='list_2019', ascending=False)
    work['industry'] = work['industry'].apply(lambda x: myreplace(x))
    x_axis = work['industry'].values.tolist()
    year = str(year)
    d1 = work['list_' + year].tolist()
    bar0 = (
        Bar()
        .add_xaxis(x_axis)
        .add_yaxis(year, d1)
        .set_global_opts(
            title_opts=opts.TitleOpts(title=year + city + fenlei),
            legend_opts=opts.LegendOpts(type_='scroll', pos_left='20%', pos_top='30'),
            yaxis_opts=opts.AxisOpts(name='万元'),
            xaxis_opts=opts.AxisOpts(name='指标', axislabel_opts=opts.LabelOpts(rotate=-30)),
            toolbox_opts=opts.ToolboxOpts(),
            # datazoom_opts=opts.DataZoomOpts(orient="vertical"),
        )
        .set_series_opts(
            # label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                    opts.MarkPointItem(type_="average", name="平均值"),
                ]
            ),
        )
    )
    return bar0


def pie_base(industry, city, year) -> Pie:
    year = str(year)
    mydata = GetData()
    data = mydata.get_data(industry)
    data = data.query('city == "{}"'.format(city))
    data['industry'] = data['industry'].apply(lambda x: myreplace(x))
    pie_bar_data = data[['industry', 'list_' + year]].set_index('industry').to_dict()['list_' + year]
    pie_bar_data = list(pie_bar_data.items())
    pie_bar = (
        Pie()
        .add("{}".format(city), data_pair=pie_bar_data, center=["80%", "30%"], radius="28%", )
        .set_global_opts(legend_opts=opts.LegendOpts(type_='scroll', is_show=False))
        .set_series_opts(tooltip_opts=opts.TooltipOpts(is_show=True, trigger="item"))
    )
    return pie_bar


@app.route('/bar_over_line')
def bar_over_line():
    bar_line_data = GetData()
    line_data0 = bar_line_data.df.query('industry == "信息传输、软件和信息技术服务业城镇单位就业人员" and city == "甘肃"')
    line_data1 = bar_line_data.df.query('industry == "信息传输、软件和信息技术服务业城镇单位就业人员平均工资" and city == "甘肃"')
    line_data2 = bar_line_data.df.query('industry == "信息传输、软件和信息技术服务业城镇私营单位就业人员平均工资" and city == "甘肃"')
    y_data0 = []
    y_data1 = []
    y_data2 = []
    x_data = []
    # display(line_data1)
    for i in range(3, 12):
        y_data0.append(str(line_data0.iloc[0, i]))
        y_data1.append(str(line_data1.iloc[0, i]))
        y_data2.append(str(line_data2.iloc[0, i]))
        x_data.append(str(2009 + i))
    print(y_data0)
    line = (
        Line()
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name="就业人员",
            y_axis=y_data0,
            yaxis_index=1
        )
    )
    bar_line = (
        Bar()
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis("城镇就业工资", y_data1)
        .add_yaxis("城镇私营工资", y_data2)
        .extend_axis(
            yaxis=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(formatter="{value} 万人"), interval=0.5
            )
        )
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="甘肃省计算机类工作"),
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} 元")),
        )
    )
    bar_line.overlap(line)
    # bar_line.render_notebook()
    return bar_line.dump_options_with_quotes()

class AddData():
    add_huafen = None
    add_industry = None


adddata = AddData()


@app.route('/add', methods=['POST', 'GET'])
def add():
    cloud = wordcloud()
    add_data = GetData()
    fenglei = add_data.fenlei
    city = add_data.huafeng.keys()
    adddata.add_huafen = '西北'
    adddata.add_industry = '按行业分城镇单位就业人员'
    if request.method == 'POST':
        adddata.add_huafen = request.form.get('city')
        adddata.add_industry = request.form.get('fenlei')
    return render_template("add.html", fenleis=fenglei, citys=city, Cloud_options=cloud.dump_options())


@app.route('/add_pie')
def shiye():
    mydata_pie = GetData()
    shiye = mydata_pie.shiye
    huafen = adddata.add_huafen
    citys = mydata_pie.huafeng
    city = citys[huafen]
    mydata = shiye.query('industry == "城镇登记失业率"')
    add_query = ''
    for item in city:
        add_query = add_query + 'city == "{}" or '.format(item)
    add_query = add_query[:-3]
    mydata = mydata.query(add_query)
    piedata = mydata[['city', 'list_2020']].set_index('city').to_dict()['list_2020']
    piedata = list(piedata.items())
    pie_0 = (
        Pie()
        .add("失业率", data_pair=piedata,
             rosetype="radius",
             radius="55%",
             center=["50%", "50%"],
             label_opts=opts.LabelOpts(is_show=False, position="center"), )
        .set_global_opts(title_opts=opts.TitleOpts(title="{}失业率比较".format(huafen)),
                         legend_opts=opts.LegendOpts('plain', is_show=False))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"),
                         tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)")
                         )

    )
    return pie_0.dump_options_with_quotes()


@app.route('/Sunburst')
def grid_mutil_yaxis() -> Sunburst:
    # city_x = ["甘肃", "陕西", "新疆", "青海", "宁夏"]
    huafen = adddata.add_huafen
    industry = adddata.add_industry
    sunburst_data = []
    sub_data = GetData()
    work_hangye_sige = sub_data.get_data(industry)
    city_x = sub_data.huafeng[huafen]
    work_hangye_sige['industry'] = work_hangye_sige['industry'].apply(lambda x: myreplace(x))
    for c in city_x:
        sunburst_dict_data = dict.fromkeys(('name', 'children'))
        children_list = []
        datas = work_hangye_sige.query('city == "{}"'.format(c))
        for index, data in datas.iterrows():
            children_dict_data = dict.fromkeys(('name', 'value'))
            children_dict_data['name'] = data['industry']
            children_dict_data['value'] = data['list_2019']
            children_list.append(children_dict_data)
        sunburst_dict_data['name'] = c
        sunburst_dict_data['children'] = children_list
        sunburst_data.append(sunburst_dict_data)
    mysunburst = (
        Sunburst(init_opts=opts.InitOpts(width="1000px", height="600px"))
        .add(
            "",
            data_pair=sunburst_data,
            highlight_policy="ancestor",
            radius=[0, "95%"],
            sort_="null",
            levels=[
                {},
                {
                    "r0": "15%",
                    "r": "35%",
                    "itemStyle": {"borderWidth": 2},
                    "label": {"rotate": "tangential"},
                },
                {"r0": "35%", "r": "70%", "label": {"align": "right"}},
                {
                    "r0": "70%",
                    "r": "72%",
                    "label": {"position": "outside", "padding": 3, "silent": False},
                    "itemStyle": {"borderWidth": 3},
                },
            ],
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="{}{}".format(huafen, industry)))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}"))
    )
    return mysunburst.dump_options_with_quotes()


def wordcloud() -> WordCloud:
    mydata = GetData()
    wordcloud_data = mydata.work_hangye_chengzhen.query('city == "陕西"')

    def fun(x):
        x = x.replace('城镇单位就业人员', '')
        return x

    wordcloud_data['industry'] = wordcloud_data['industry'].apply(lambda x: fun(x))
    # display(wordcloud_data)
    wordcloud_data = wordcloud_data[['industry', 'list_2020']].set_index('industry').to_dict()['list_2020']
    wordcloud_data = list(wordcloud_data.items())
    wordcloud = (
        WordCloud(init_opts=opts.InitOpts(width="1280px", height="720px", bg_color="#CCCCCC"))
        .add(
            "",
            wordcloud_data,
            # word_size_range=[61, 200],
            textstyle_opts=opts.TextStyleOpts(font_family="cursive"),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="陕西城镇就业单位人员"))
    )
    # wordcloud.render_notebook()
    return wordcloud


@app.route('/add_rader', methods=['POST', 'GET'])
def add_rader():
    add_rader_data = GetData()
    industry = adddata.add_industry
    citys = adddata.add_huafen
    city = add_rader_data.huafeng[citys]
    # print(city, industry)
    data_ = add_rader_data.get_data(industry)
    data_ = data_.query('city == "{}"'.format(city[0]))
    # data_ = add_rader_data.df.query('industry == "{}" and city == "{}"'.format(industry, city[0]))
    data_ = data_.sort_values(by='list_2020', ascending=False)
    data_ = data_.head(6)
    industrys = data_['industry'].values.tolist()
    # print('最大', max_data)
    # print(industrys)
    radar_data = add_rader_data.df.query('industry == "{}" or industry == "{}" or industry == "{}"\
                or industry == "{}"or industry == "{}"or industry == "{}"'.format(industrys[0], industrys[1],
                                                                                  industrys[2], industrys[3],
                                                                                  industrys[4], industrys[5]))
    max_data = radar_data.sort_values(by='list_2020', ascending=False)
    max_data = max_data.head(6)
    max_data = max_data['list_2020'].values.tolist()
    for i in range(6):
        max_data[i] += 20
    # print(len(city))
    if len(city) == 3:
        radar_data0 = radar_data.query('city == "{}"'.format(city[0]))
        radar_data1 = radar_data.query('city == "{}"'.format(city[1]))
        radar_data2 = radar_data.query('city == "{}"'.format(city[2]))
        radar_listdata1 = [radar_data0['list_2020'].values.tolist()]
        radar_listdata2 = [radar_data1['list_2020'].values.tolist()]
        radar_listdata3 = [radar_data2['list_2020'].values.tolist()]
        radar = (
            Radar(init_opts=opts.InitOpts(width="1280px", height="720px"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=industrys[0], max_=max_data[0]),
                    opts.RadarIndicatorItem(name=industrys[1], max_=max_data[1]),
                    opts.RadarIndicatorItem(name=industrys[2], max_=max_data[2]),
                    opts.RadarIndicatorItem(name=industrys[3], max_=max_data[3]),
                    opts.RadarIndicatorItem(name=industrys[4], max_=max_data[4]),
                    opts.RadarIndicatorItem(name=industrys[5], max_=max_data[5]),
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
                textstyle_opts=opts.TextStyleOpts(color="#2b2b2b"),
            )
            .add(
                series_name="{}".format(city[0]),
                data=radar_listdata1,
                linestyle_opts=opts.LineStyleOpts(color="#fb932f"),
            )
            .add(
                series_name="{}".format(city[1]),
                data=radar_listdata2,
                linestyle_opts=opts.LineStyleOpts(color="#1bb6ec"),
            )
            .add(
                series_name="{}".format(city[2]),
                data=radar_listdata3,
                linestyle_opts=opts.LineStyleOpts(color="#CD0000"),
            )
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="基础雷达图"), legend_opts=opts.LegendOpts()
            )
        )
        return radar.dump_options_with_quotes()
    if len(city) == 5:
        radar_data0 = radar_data.query('city == "{}"'.format(city[0]))
        radar_data1 = radar_data.query('city == "{}"'.format(city[1]))
        radar_data2 = radar_data.query('city == "{}"'.format(city[2]))
        radar_data3 = radar_data.query('city == "{}"'.format(city[3]))
        radar_data4 = radar_data.query('city == "{}"'.format(city[4]))
        radar_listdata1 = [radar_data0['list_2020'].values.tolist()]
        radar_listdata2 = [radar_data1['list_2020'].values.tolist()]
        radar_listdata3 = [radar_data2['list_2020'].values.tolist()]
        radar_listdata4 = [radar_data3['list_2020'].values.tolist()]
        radar_listdata5 = [radar_data4['list_2020'].values.tolist()]
        radar = (
            Radar(init_opts=opts.InitOpts(width="1280px", height="720px"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=industrys[0], max_=max_data[0]),
                    opts.RadarIndicatorItem(name=industrys[1], max_=max_data[1]),
                    opts.RadarIndicatorItem(name=industrys[2], max_=max_data[2]),
                    opts.RadarIndicatorItem(name=industrys[3], max_=max_data[3]),
                    opts.RadarIndicatorItem(name=industrys[4], max_=max_data[4]),
                    opts.RadarIndicatorItem(name=industrys[5], max_=max_data[5]),
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
                textstyle_opts=opts.TextStyleOpts(color="#2b2b2b"),
            )
            .add(
                series_name="{}".format(city[0]),
                data=radar_listdata1,
                linestyle_opts=opts.LineStyleOpts(color="#fb932f"),
            )
            .add(
                series_name="{}".format(city[1]),
                data=radar_listdata2,
                linestyle_opts=opts.LineStyleOpts(color="#1bb6ec"),
            )
            .add(
                series_name="{}".format(city[2]),
                data=radar_listdata3,
                linestyle_opts=opts.LineStyleOpts(color="#CD0000"),
            )
            .add(
                series_name="{}".format(city[3]),
                data=radar_listdata4,
                linestyle_opts=opts.LineStyleOpts(color="#3b702c"),
            )
            .add(
                series_name="{}".format(city[4]),
                data=radar_listdata5,
                linestyle_opts=opts.LineStyleOpts(color="#0d293e"),
            )
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="基础雷达图"), legend_opts=opts.LegendOpts()
            )
        )
        return radar.dump_options_with_quotes()
    if len(city) == 7:
        radar_data0 = radar_data.query('city == "{}"'.format(city[0]))
        radar_data1 = radar_data.query('city == "{}"'.format(city[1]))
        radar_data2 = radar_data.query('city == "{}"'.format(city[2]))
        radar_data3 = radar_data.query('city == "{}"'.format(city[3]))
        radar_data4 = radar_data.query('city == "{}"'.format(city[4]))
        radar_data5 = radar_data.query('city == "{}"'.format(city[5]))
        radar_data6 = radar_data.query('city == "{}"'.format(city[6]))
        radar_listdata1 = [radar_data0['list_2020'].values.tolist()]
        radar_listdata2 = [radar_data1['list_2020'].values.tolist()]
        radar_listdata3 = [radar_data2['list_2020'].values.tolist()]
        radar_listdata4 = [radar_data3['list_2020'].values.tolist()]
        radar_listdata5 = [radar_data4['list_2020'].values.tolist()]
        radar_listdata6 = [radar_data5['list_2020'].values.tolist()]
        radar_listdata7 = [radar_data6['list_2020'].values.tolist()]
        print(radar_listdata1)
        radar = (
            Radar(init_opts=opts.InitOpts(width="1280px", height="720px"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=industrys[0], max_=max_data),
                    opts.RadarIndicatorItem(name=industrys[1], max_=max_data),
                    opts.RadarIndicatorItem(name=industrys[2], max_=max_data),
                    opts.RadarIndicatorItem(name=industrys[3], max_=max_data),
                    opts.RadarIndicatorItem(name=industrys[4], max_=max_data),
                    opts.RadarIndicatorItem(name=industrys[5], max_=max_data),
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
                textstyle_opts=opts.TextStyleOpts(color="#2b2b2b"),
            )
            .add(
                series_name="{}".format(city[0]),
                data=radar_listdata1,
                linestyle_opts=opts.LineStyleOpts(color="#fb932f"),
            )
            .add(
                series_name="{}".format(city[1]),
                data=radar_listdata2,
                linestyle_opts=opts.LineStyleOpts(color="#1bb6ec"),
            )
            .add(
                series_name="{}".format(city[2]),
                data=radar_listdata3,
                linestyle_opts=opts.LineStyleOpts(color="#CD0000"),
            )
            .add(
                series_name="{}".format(city[3]),
                data=radar_listdata4,
                linestyle_opts=opts.LineStyleOpts(color="#3b702c"),
            )
            .add(
                series_name="{}".format(city[4]),
                data=radar_listdata5,
                linestyle_opts=opts.LineStyleOpts(color="#0d293e"),
            )
            .add(
                series_name="{}".format(city[5]),
                data=radar_listdata6,
                linestyle_opts=opts.LineStyleOpts(color="#0076f6"),
            )
            .add(
                series_name="{}".format(city[6]),
                data=radar_listdata7,
                linestyle_opts=opts.LineStyleOpts(color="#2d2e7e"),
            )
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="基础雷达图"), legend_opts=opts.LegendOpts()
            )
        )
        return radar.dump_options_with_quotes()


@app.route('/map', methods=['POST', 'GET'])
def mmap():
    mydata = GetData()
    fenleis = mydata.fenlei_min
    citys = mydata.city
    data.map_data = '信息传输、软件和信息技术服务业城镇单位就业人员'
    data.map_city = '甘肃'
    if request.method == "POST":
        data.map_data = request.form.get('fenleis_wake')
        data.map_city = request.form.get('fenleis_city')
    return render_template('map.html', citys=citys, fenleis_wake=fenleis)


@app.route('/map1')
def map0():
    map_data = data.map_data
    map = MyMap(map_data, 100)
    return map.dump_options_with_quotes()


@app.route('/map2')
def map2():
    map_data = data.map_data
    map_data = map_data.replace('城镇单位就业人员', '城镇单位就业人员平均工资')
    map = MyMap(map_data, 300000)
    return map.dump_options_with_quotes()


@app.route('/map3')
def map3():
    map_data = data.map_data
    map_data = map_data.replace('城镇单位就业人员', '城镇私营单位就业人员平均工资')
    map = MyMap(map_data, 300000)
    return map.dump_options_with_quotes()


@app.route('/Liquid1')
def Liquid0():
    city = data.map_city
    industry = data.map_data
    timeline = Timeline(init_opts=opts.InitOpts(width="1600px", height="900px"))

    for y in range(2012, 2021):
        timeline.add(Liqiuid(city=city, industry=industry, year=y, lei='城镇单位人员'), time_point=str(y))
    timeline.add_schema(is_timeline_show=False, orient='vertical', is_auto_play=True, play_interval=1500, pos_left='10',
                        pos_top='10')
    liquid = myUpdateJsCode(timeline.dump_options_with_quotes())
    return liquid


@app.route('/Liquid2')
def Liquid2():
    city = data.map_city
    map_data = data.map_data
    industry = map_data.replace('城镇单位就业人员', '城镇单位就业人员平均工资')
    timeline = Timeline(init_opts=opts.InitOpts(width="1600px", height="900px"))

    for y in range(2012, 2021):
        timeline.add(Liqiuid(city=city, industry=industry, year=y, lei='城镇单位平均工资'), time_point=str(y))
    timeline.add_schema(is_timeline_show=False, orient='vertical', is_auto_play=True, play_interval=1500, pos_left='10',
                        pos_top='10')
    liquid = myUpdateJsCode(timeline.dump_options_with_quotes())
    return liquid


@app.route('/Liquid3')
def Liquid3():
    city = data.map_city
    map_data = data.map_data
    industry = map_data.replace('城镇单位就业人员', '城镇私营单位就业人员平均工资')
    timeline = Timeline(init_opts=opts.InitOpts(width="1600px", height="900px"))

    for y in range(2012, 2021):
        timeline.add(Liqiuid(city=city, industry=industry, year=y, lei='城镇私营单位平均工资'), time_point=str(y))
    timeline.add_schema(is_timeline_show=False, orient='vertical', is_auto_play=True, play_interval=1500, pos_left='10',
                        pos_top='10')
    liquid = myUpdateJsCode(timeline.dump_options_with_quotes())
    return liquid


@app.route('/map_funnel')
def map_funnel():
    map_funnel_data = GetData()
    funnel_data = map_funnel_data.work_hangye_chengzhen.query('city == "陕西"')

    # def fun(x):
    #     x = x.replace('城镇单位就业人员', '')
    #     return x
    #
    funnel_data['industry'] = funnel_data['industry'].apply(lambda x: myreplace(x))
    # display(wordcloud_data)
    funnel_data = funnel_data[['industry', 'list_2020']].set_index('industry').to_dict()['list_2020']
    funnel_data = list(funnel_data.items())
    # print(funnel_data)
    funnel = (
        Funnel()
        .add(
            "万人",
            funnel_data,
            sort_="ascending",
            label_opts=opts.LabelOpts(position="inside"),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="陕西省-城镇单位就业人员")
                         , legend_opts=opts.LegendOpts(type_='scroll', pos_top=30, is_show=False))
    )
    return funnel.dump_options_with_quotes()


def MyMap(industry, map_max):
    timeline = Timeline(init_opts=opts.InitOpts(width="1600px", height="900px"))

    for y in range(2012, 2021):
        timeline.add(map1(industry=industry, year=y, map_max=map_max), time_point=str(y))
    timeline.add_schema(is_timeline_show=False, orient='vertical', is_auto_play=True, play_interval=1500, pos_left='10',
                        pos_top='10')

    return timeline


def map1(industry, year, map_max):
    my_map_data = GetData()
    map_data = my_map_data.df
    map_data = map_data.query('industry == "{}"'.format(industry))
    tityear = year
    year = 'list_' + str(year)
    map_data = map_data[['city', year]].set_index('city').to_dict()[year]
    map_data = list(map_data.items())
    map_lx = (
        Map()
        # .add("就业人员人员", map_data, "china", is_selected=False, layout_center=['75%', '50%'], layout_size=400)
        .add("就业人员", map_data, "china")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="中国{}{}".format(tityear, industry)),
            visualmap_opts=opts.VisualMapOpts(max_=map_max, split_number=10, is_piecewise=True),
        )
    )

    return map_lx


Liquid_data = GetData()


def Liqiuid(city, industry, year, lei):
    l1_data = Liquid_data.df.query('industry == "{}"'.format(industry))
    # print('0', l1_data)
    l1_data_n = l1_data.query('city == "{}"'.format(city))
    # print('1', l1_data_n)
    i = year - 2012 + 3
    n = l1_data_n.iloc[0, i]
    num = 0
    tityear = year
    year = 'list_' + str(year)
    for item in l1_data[year]:
        num += item
    LQ_data = n / num
    l1 = (
        Liquid()
        .add("{}占比".format(city), [LQ_data],
             label_opts=opts.LabelOpts(
                 font_size=50,
                 formatter=JsCode(
                     """  function (param) {
                             return (Math.floor(param.value * 10000) / 100) + '%';
                         }"""
                 ),
                 position="inside",
             ),
             )
        .set_global_opts(title_opts=opts.TitleOpts(title="{}{}{}".format(city, tityear, lei)))
    )
    return l1


def myUpdateJsCode(strSrc):
    strOut = strSrc
    bOK = False
    while bOK == False:
        re_ser = re.search("\"\s*function", strOut)
        if re_ser:
            index = re_ser.span()[0]
            strOut = strOut[:index] + strOut[index + 1:]
            iend = strOut.index("\"", index)  # 遍历下一个",function不能再有双引号
            strOut = strOut[:iend] + strOut[iend + 1:]
        else:
            bOK = True
    return strOut


if __name__ == '__main__':
    app.run()
